package com.wangsd.web.mqpay.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.ODDGenerator;
import com.wangsd.web.mqpay.entity.Customer;
import com.wangsd.web.mqpay.entity.Passageway;
import com.wangsd.web.mqpay.entity.Trade;
import com.wangsd.web.mqpay.mapper.CustomerMapper;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.service.SysCompanyService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CustomerService {
    @Resource
    private CustomerMapper mapper;
    @Autowired
    private SysCompanyService companyService;
    @Autowired
    private CustomerFlowService customerFlowService;
    @Autowired
    private PassagewayService passagewayService;

    private Customer selectByName(String name, Long id) {
        Query query = new Query();
        query.eq("name", name);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }


    public Customer selectByCode(String code) {
        return mapper.getByColumn("code", code);
    }

    public List<Customer> selectPage(Customer queryObj, String code) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getName())) {
            query.like("name", queryObj.getName());
        }
        if (StringUtils.isNotBlank(queryObj.getParentCode())) {
            query.likeRight("code", queryObj.getParentCode());
        }
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("code", code);
        }

        List<Customer> list = mapper.list(query);
        return list;
    }

    @Transactional
    public int saveOrUpdate(Customer entity) {
        Customer agent = this.selectByName(entity.getName(), entity.getId());
        if (agent != null) {
            throw new BusinessException("名称不能重复！");
        }

        if (entity.getId() == null) {
            entity.setCustomerNo(ODDGenerator.getClientNo(StringUtils.replace(UUID.randomUUID().toString(), "-", "")));
            entity.setApiKey(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
            mapper.saveIgnoreNull(entity);
            entity.setCode(entity.getParentCode() + "-" + entity.getId());
            mapper.updateIgnoreNull(entity);
        } else {
            mapper.updateIgnoreNull(entity);
        }

        return 1;
    }

    @Transactional
    public int delete(Long id) {
        return mapper.deleteById(id);
    }

    /**
     * 根据code查询所有能看到的客户(商圈)
     *
     * @param code
     * @return
     */
    public List<Customer> selectAllCustomer(String code, String code2) {
        Query query = new Query();
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("code", code);
        }
        if (StringUtils.isNotBlank(code2)) {
            query.likeRight("code", code2);
        }
        return mapper.list(query);
    }

    public Customer selectById(Long id) {
        return mapper.getById(id);
    }

    public Customer selectByCustomerNo(String customerNo) {
        Query query = new Query();
        query.eq("customer_no", customerNo);
        return mapper.getByQuery(query);
    }
    /**
     * 根据parentCode查询所有
     *
     * @param parentCode
     * @return
     */
    public List<Customer> selectByParentCode(String parentCode) {
        return mapper.listByColumn("parent_code", parentCode);
    }
    /**
     * 刷新api秘钥
     *
     * @param id
     * @return
     */
    public Map refreshApi(Long id) {
        Customer customer = new Customer();
        customer.setId(id);
        String apikey = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        customer.setApiKey(apikey);
        mapper.updateIgnoreNull(customer);
        Map map = new HashMap();
        map.put("apiKey", apikey);
        return map;
    }

    /**
     * 申请提现
     *
     * @param id
     * @param settleAmount
     */
    @Transactional
    public int createCustomerFlow(Long id, Integer settleAmount) {
        if (settleAmount <= 0) {
            throw new BusinessException("提现金额不能小于0");
        }
        Customer customer = this.selectById(id);
        if (settleAmount > customer.getUseableAmount()) {
            throw new BusinessException("提现金额不能大于可用余额");
        }
        customer.setUseableAmount(customer.getUseableAmount() - settleAmount);
        mapper.updateIgnoreNull(customer);

        return customerFlowService.save(id, settleAmount);
    }

    /**
     * 计算平台收入
     * @param trade
     */
    @Transactional
    public void updateCustomerAmount(Trade trade) {
        Customer customer = this.selectByCode(trade.getParentCode());
        Passageway passageway = passagewayService.selectByCustomerNoAndPayCode(customer.getCode(), trade.getPayCode());
        BigDecimal rate = new BigDecimal("1").subtract(passageway.getRate());
        //商户可用余额
        Integer useableAmount = (int) ((trade.getAmount() * rate.doubleValue()));
        //平台利润(手续费)
        Integer profitAmount = trade.getAmount() - useableAmount;
//        customer.setUseableAmount(customer.getUseableAmount() + useableAmount);
//        customer.setProfitAmount(customer.getProfitAmount() + profitAmount);
        mapper.updateUseableAndProfit(useableAmount, profitAmount, customer.getId());

        //计算代理商技术服务费
        SysCompany company = companyService.selectByCode(customer.getParentCode());
        if (company.getType() == 2) {
            Integer amount = (int) ((trade.getAmount() * company.getRate().doubleValue()));
            companyService.updateProfitAmount(amount, company.getId());
        }
    }

}
